import { useSetState } from "ahooks";
import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import {
  OPTION_ACTION,
  defaultRecordActionState,
  defaultTransformState,
  defaultVoiceLen,
} from "./store";
import { IRecordActionState, ITransformState } from "types/TextInput";
import { requirePlugin } from "@tarojs/taro";
import Taro from "@tarojs/taro";
import { ChatContext } from "@/pages/index/hooks/store";

//引入插件：微信同声传译
const plugin = requirePlugin("WechatSI");
//获取全局唯一的语音识别管理器recordRecoManager
const manager = plugin.getRecordRecognitionManager();

type TActionState = "default" | "record" | "transform" | "wait";

function useVoiceInput() {
  const { handle } = useContext(ChatContext);

  const [touchTime, setTouchTime] = useSetState<{
    touchStartTime: number;
    touchEndTime: number;
  }>({
    touchStartTime: 0,
    touchEndTime: 0,
  });

  // 延迟语音识别，防止用户快速点击
  const [sTimerId, setStimerId] = useState<any>(null);
  // 录音
  const [timerId, setTimerId] = useState<any>(null);
  const maskVisibleRef = useRef<any>(null);
  // 遮罩
  const [maskVisible, setMaskVisible] = useState(false);
  maskVisibleRef.current = maskVisible;
  const [hasRecordRole, setHasRecordRole] = useState(false);
  // 当前操作状态
  const [actionState, setActionState] = useState<TActionState>("default");
  // 录音时的操作状态
  const [recordActionState, setRecordActionState] =
    useSetState<IRecordActionState>({
      ...defaultRecordActionState,
    });

  // 语音录制时间长度（关系到展示的语音样式）： 这边默认1
  const [voiceLen, setVoiceLen] = useState(defaultVoiceLen);
  const [startState, setStartState] = useSetState({
    startX: 0,
    startY: 0,
  });

  const [transformState, setTransformState] = useSetState<ITransformState>({
    ...defaultTransformState,
  });

  const initTimer = () => {
    clearTimeout(sTimerId);
    clearInterval(timerId);
    setStimerId(null);
    setTimerId(null);
  };

  const closeMask = () => {
    console.log("closeMask start");
    // manager.stop();
    if (transformState.recordState) {
      console.log("需要关闭 manager");
      manager.stop();
    }
    initTimer();
    setActionState("default");
    setHasRecordRole(false);
    setTouchTime({
      touchStartTime: 0,
      touchEndTime: 0,
    });
    setRecordActionState({
      ...defaultRecordActionState,
    });
    setTransformState({
      ...defaultTransformState,
    });
    setVoiceLen(defaultVoiceLen);

    setStartState({
      startX: 0,
      startY: 0,
    });
    setMaskVisible(false);
    maskVisibleRef.current = false;
    console.log("closeMask end");
  };

  const handleRecorderManager = () => {
    setMaskVisible(true);
    maskVisibleRef.current = true;
    setHasRecordRole(true);
    setActionState("record");
    initTimer();
    setVoiceLen(defaultVoiceLen);

    let currentLength = 1;
    let sT = setTimeout(() => {
      console.log(
        "handleRecorderManager maskVisibleRef.current",
        maskVisibleRef.current
      );
      console.log("handleRecorderManager maskVisible", maskVisible);
      if (!maskVisibleRef.current) {
        closeMask();
        return;
      }
      // 语音开始识别
      manager.start({
        lang: "zh_CN", // 识别的语言，目前支持zh_CN en_US zh_HK sichuanhua
      });
    }, 500);
    setStimerId(sT);
    // 语音开始识别
    // manager.start({
    //   lang: "zh_CN", // 识别的语言，目前支持zh_CN en_US zh_HK sichuanhua
    // });
    let timer = setInterval(() => {
      currentLength += 1;
      setVoiceLen(currentLength);
      if (currentLength >= 60) {
        clearInterval(timer);
        handleTouchEnd();
      }
    }, 1000);
    setTimerId(timer);
  };
  const handleTouchStart = (e) => {
    console.log("handleTouchStart");
    console.log("touchStartTime", e.timeStamp);
    setTouchTime({
      touchStartTime: new Date().getTime(),
    });
    setTransformState({
      ...defaultTransformState,
    });
    const eTouches = e.touches[0];
    setStartState({
      startX: eTouches.pageX,
      startY: eTouches.pageY,
    });

    handleRecorderManager();
  };

  const handleTouchMove = (e) => {
    e.stopPropagation();
    console.log("handleTouchMove");
    const eTouches = e.touches[0];
    if (
      startState.startX - eTouches.pageX > 14 && // 左边
      startState.startY - eTouches.pageY > 50
    ) {
      setRecordActionState({
        toCancel: true,
        toTransform: false,
      });
    } else if (
      startState.startX - eTouches.pageX < 14 && // 右边
      startState.startY - eTouches.pageY > 50
    ) {
      setRecordActionState({
        toCancel: false,
        toTransform: true,
      });
    } else {
      setRecordActionState({
        toCancel: false,
        toTransform: false,
      });
    }
  };
  /**
   * @description: 开启翻译标识
   * @return {*}
   */
  const toTransForm = () => {
    initTimer();
    setTransformState({
      isTransform: true,
    });
    setActionState("transform");
  };

  const handleTouchEnd = (e?) => {
    console.log("handleTouchEnd");
    e?.stopPropagation();
    setTimeout(() => {
      let touchEndTime = new Date().getTime();
      console.log("handleTouchEnd", touchEndTime);

      if (touchEndTime - touchTime.touchStartTime < 500) {
        console.log("handleTouchEnd 请按住说话", touchEndTime);

        Taro.showToast({
          title: "请按住说话",
          icon: "none",
          duration: 1000,
        });
        closeMask();
        return;
      }
      clearTimeout(sTimerId);
      setStimerId(null);
      clearInterval(timerId);
      setTimerId(null);
      // 语音结束识别
      manager.stop();
      console.log("recordActionState", recordActionState);
      if (recordActionState.toCancel) {
        console.log("recordActionState 1");

        // 取消发送： 直接关闭弹窗
        setRecordActionState({
          toCancel: false,
        });
        setMaskVisible(false);
        maskVisibleRef.current = false;
        setHasRecordRole(false);
        closeMask();
      } else if (recordActionState.toTransform) {
        console.log("recordActionState 2");

        // 语音转换为文字
        setRecordActionState({
          toTransform: false,
        });
        if (hasRecordRole) {
          toTransForm();
        }
      } else {
        console.log("recordActionState 3");

        closeMask();
      }
    }, 200);
  };

  // 计算语音条宽度
  const voiceBarWidth = useMemo(() => {
    return 230 + voiceLen * 4 + "rpx";
  }, [voiceLen]);

  const isOptionAction = useMemo(() => {
    return OPTION_ACTION.includes(actionState);
  }, [actionState]);

  const sendMsg = () => {
    console.log("发送 msg", transformState.content);
    closeMask();
    handle(transformState.content);
  };

  const initRecord = () => {
    manager.onRecognize = (res) => {
      console.log("onRecognize", res);
    };
    manager.onStart = (res) => {
      console.log("onStart maskVisible", maskVisible);
      console.log("onStart maskVisibleRef", maskVisibleRef.current);
      // if (!maskVisibleRef.current.maskVisible) {
      //   closeMask();
      //   return;
      // }
      setTransformState({
        recordState: true,
      });
      console.log("成功开始录音识别", res);
    };
    manager.onError = (res) => {
      console.error("录音识别 error", res);
      Taro.showModal({
        title: "提示",
        content: `录音识别 error:${res.msg}}`,
        showCancel: false,
        success: function () {
          closeMask();
        },
      });
    };
    manager.onStop = (res) => {
      console.log("..............结束录音");
      console.log("录音临时文件地址 -->" + res.tempFilePath);
      console.log("录音总时长 -->" + res.duration + "ms");
      console.log("文件大小 --> " + res.fileSize + "B");
      console.log("语音内容 --> " + res.result);
      setTransformState({
        isTransform: false,
      });
      setActionState("wait");
      if (res.result == "") {
        setTransformState({
          type: 1,
          recordState: false,
          content: "未识别到文字",
        });
      } else {
        const text = transformState.content + res.result;
        setTransformState({
          type: 2,
          content: text,
          recordState: false,
        });
      }
    };
  };

  const checkRecordRole = () => {
    Taro.getSetting({
      success(res) {
        if (!res.authSetting["scope.record"]) {
          Taro.authorize({
            scope: "scope.record",
            success() {
              // 用户已同意授权
              console.log("用户已同意授权");
            },
            fail() {
              // 用户拒绝了授权
              console.log("用户拒绝了授权");
              Taro.showModal({
                title: "提示",
                content: "需要获取录音权限，请点击确定进入设置页面进行授权。",
                showCancel: false,
                success(res) {
                  if (res.confirm) {
                    Taro.openSetting({
                      success(res) {
                        console.log(res.authSetting);
                        // 用户在设置页面设置了录音权限
                        if (res.authSetting["scope.record"]) {
                          console.log("用户在设置页面设置了录音权限");
                        } else {
                          console.log("用户在设置页面未设置录音权限");
                        }
                      },
                    });
                  }
                },
              });
            },
          });
        } else {
          // 已经有权限
          console.log("已经有录音权限");
        }
      },
    });
  };
  useEffect(() => {
    checkRecordRole();
    initRecord();
    closeMask();
  }, []);

  console.log("current maskVisibleRef", maskVisibleRef.current);
  return {
    maskVisible,
    voiceBarWidth,
    actionState,
    isOptionAction,
    transformState,
    recordActionState,
    setMaskVisible,
    handleTouchStart,
    handleTouchMove,
    handleTouchEnd,
    closeMask,
    sendMsg,
    setTransformState,
    setRecordActionState,
  };
}

export default useVoiceInput;
